package main

import (
	"log"
	"net"
	"strconv"
	"strings"
	"time"
)

func main() {

	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		panic(err)
	}

	for {
		conn, err := listener.Accept()
		if err != nil {
			panic(err)
		}

		for i := 0; i < 5; i++ {
			go readFromConn(conn, strconv.Itoa(i))
			go writeToConn(conn, strconv.Itoa(i))
		}

	}
}

func writeToConn(conn net.Conn, appId string) {
	for {
		str := appId + "_" + strings.Repeat("a", 10)

		wl, err := conn.Write([]byte(str))
		if err != nil {
			log.Println(err)
			continue
		}
		log.Printf("[server]对端写入数据: %s, 长度: %d\n", str, wl)

		time.Sleep(3 * time.Second)
	}
}

func readFromConn(conn net.Conn, appId string) {
	for {
		recvbuf := make([]byte, 1024)

		rl, err := conn.Read(recvbuf)

		if err != nil {
			log.Println(err)
			continue
		}

		recvbytes := recvbuf[:rl]
		recvContent := string(recvbytes)
		log.Printf("[server]appId: %s, 从对端接收到的数据: %s, 长度: %d\n", appId, recvContent, rl)
	}
}
